import { TableProps } from '@/components'
import { Operate } from '@/enums'
import { CustomParams } from '@/types'
import { formatRequestParams, getURLSearchString } from '@/utils'
import type { PaginationProps } from 'antd'
import { SorterResult } from 'antd/es/table/interface'
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'

export const useTable = (service, urlParams = {}, extraParams = {}, format = true) => {
  const paramsRef = useRef<CustomParams>({ page: 1, page_size: 10 })
  const [tableData, setTableData] = useState([])
  const [tableDataTotal, setTableDataTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [loading, setLoading] = useState(false)

  const query = useCallback(
    _params => {
      setPage(1)
      paramsRef.current = { ..._params, page: 1, page_size: pageSize }
      fetchData()
    },
    [pageSize]
  )

  const turnPage = (page, pageSize) => {
    setPage(page)
    setPageSize(pageSize)
    paramsRef.current = { ...paramsRef.current, page, page_size: pageSize }
    fetchData()
  }

  const pagination: PaginationProps = {
    showQuickJumper: true,
    showSizeChanger: true,
    total: tableDataTotal,
    onChange: turnPage,
    showTotal(total, range) {
      if (range[1] === range[0]) {
        return `第${range[0]}条/总共${total}条`
      } else {
        return `第${range[0]}-${range[1]}条/总共${total}条`
      }
    },
    current: page,
    pageSize
  }

  const refresh = () => fetchData()

  const fetchData = (urlParams = {}) => {
    setLoading(true)
    paramsRef.current = { ...paramsRef.current, ...urlParams }
    return service(
      format ? formatRequestParams({ ...paramsRef.current, ...extraParams }) : { ...paramsRef.current, ...extraParams }
    )
      .then(({ data, list = data, total = data.total }) => {
        // if (total == paramsRef.current.offset && paramsRef.current.offset > 0) {
        //   turnPage(page - 1, pageSize)
        // } else {
        // setTableData(list.map((item, idx) => {
        //   return Object.assign(item, { key: item.id || idx })
        // }))
        setTableData(list)
        setTableDataTotal(total)
        // }
      })
      .catch(err => {
        // err && message.error(err.toString())
        setTableData([])
      })
      .finally(() => {
        setLoading(false)
      })
  }

  const onChange: TableProps['onChange'] = (pagination, filters, sorter, extra) => {
    const { field, order } = sorter as SorterResult<any>
    if (!order) {
      paramsRef.current = { ...paramsRef.current, sort_field: undefined, sort_order: undefined }
    } else {
      paramsRef.current = { ...paramsRef.current, sort_field: field, sort_order: Operate.Order[order] }
    }
    fetchData()
  }

  useEffect(() => {
    fetchData(urlParams)
  }, [])

  return {
    query,
    paramsRef,
    refresh,
    dataSource: tableData,
    total: tableDataTotal,
    pagination,
    loading,
    page,
    pageSize,
    turnPage,
    onChange
  }
}
